More results...

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
post
page
◑ Python IDE Dashboard

Crack the Code – Python Challenge

Can you crack code using the above 5 clues?

The secret code consists of four unique digits, meaning that no digit appears more than once. Each clue provides a possible 4-digit combination, but there is a catch:
In each clue, exactly two digits are correct, but neither of these digits is in the correct position.

Can you use these clues to identify the secret code?

In this challenge, we will use a Python program to perform a brute attack to find the correct code.

What is a Brute Force Attack?

A brute force attack is a technique used to solve a problem by systematically trying every possible solution until the correct one is found. In cybersecurity, brute force attacks can be used to guess passwords or PIN codes by testing large numbers of possible combinations.

For a 4-digit PIN, there are 10,000 possible combinations, ranging from 0000 to 9999. Rather than testing each combination manually, we can use Python to automate the process!

Python Challenge

In this challenge, we will use a Python program to perform a brute force attack on our secret code.

The program will systematically test every possible 4-digit combination between 0000 and 9999.

For each combination, it will check that:

  • The code contains four different digits, with no repetitions.
  • For each of the six clues, exactly two digits appear in the proposed code.
  • These two matching digits are not in the same positions as in the clue.

Any combination that fails one of these checks will be rejected.

By applying all six clues, the program should eventually identify the one and only 4-digit combination that satisfies every condition.

Let’s Crack the Code!

Below, you will find the complete Python code inside our interactive Python IDE. Run the program and see how Python can solve this logic puzzle by testing thousands of possible combinations in a fraction of a second!

Will the program successfully crack the code?

Once you have discovered the secret combination, look back at the original clues and check that the answer satisfies every single one of them.

Your Challenge

Your challenge consists of tweaking the above Python code to crack the following code:

Network Addresses Quiz

When devices communicate over a network, they need to be able to identify each other so that data can be sent to the correct destination. Network addresses are used to identify devices and help ensure that data travels to the right place.

There are three main types of network addresses you need to recognise:

  • IPv4 (Internet Protocol version 4): A 32-bit address made up of four decimal numbers (0–255) separated by dots. For example: 192.168.1.100.
  • IPv6 (Internet Protocol version 6): A 128-bit address written using eight groups of hexadecimal digits separated by colons. For example: 2001:0DB8:0000:0000:0000:0000:0000:0001. IPv6 addresses can also be compressed by removing leading zeroes and shortening consecutive groups of zeroes.
  • MAC (Media Access Control) Address: A 48-bit hardware address used to identify a network interface on a local network. It is typically written as six pairs of hexadecimal digits separated by colons. For example: 00:1A:2B:3C:4D:5E.

You can find out more about network addresses by reading this blog post about IPv4, IPv6, MAC addresses, URLs and the use of Domain Name Servers on the Internet.

Your Challenge

Test your knowledge with this interactive quiz! You will be shown randomly generated network addresses. For each address, decide whether it is a valid IPv4, IPv6 or MAC address, or whether it is invalid.

Watch out for incorrect separators, invalid characters, missing digits and numbers outside the permitted range.

How many addresses can you correctly identify in a row?
Network Addresses QuizOpen this activity in a New Window

Cardinal Buoys Positioning – Python Challenge

When navigating at sea, sailors need to know where it is safe to travel and where underwater dangers such as rocks, reefs or wrecks may be hiding beneath the surface. Not every hazard can be seen from a boat, so navigation buoys are used to mark hazards and guide vessels safely around them.

In this Python challenge, you will investigate a particular type of navigation marker: the cardinal buoy. You will then use selection (if statements) and coordinates to write a program that automatically chooses the correct cardinal buoy based on its position relative to an underwater danger.

What are Cardinal Buoys?


Cardinal buoys are used to indicate where the safe water lies in relation to a hazard. They are named after the four cardinal points of a compass: North – East – South – West

The name of the buoy tells a sailor which side of the buoy they should pass. For example, a North Cardinal Buoy tells you that the safest/deepest water is to the north of the buoy, while a West Cardinal Buoy indicates that you should pass to its west.

Cardinal buoys are easy to recognise because they use distinctive black and yellow markings, together with two black triangles pointing either up ▲ or down ▼.

  • North: black above yellow, with both triangles pointing upwards.
  • East: black-yellow-black, with the triangles pointing away from each other.
  • South: yellow above black, with both triangles pointing downwards.
  • West: yellow-black-yellow, with the triangles pointing towards each other.

These markings allow sailors to quickly identify the buoy and determine where the safe water is located.

The Coding Challenge

For this challenge, an underwater rock is positioned in the centre of the screen. Your program will randomly generate a position (x, y) for a new buoy somewhere around this danger.
Your task is to determine which of the four cardinal buoys should be placed at that position.

Some of the Python code has already been provided for you. This includes the code required to draw the sea and underwater danger, as well as a subroutine called:

addBuoy(cardinalPoint, x, y)

The subroutine requires three parameters:

  1. The type of cardinal buoy: “North”, “South”, “East” or “West”
  2. Its x-coordinate
  3. Its y-coordinate

For example, the following code will draw a West Cardinal Buoy at coordinates (-100, 20):

addBuoy("West", -100, 20)

Note that the centre of the screen represents the danger and has coordinates (0, 0).

Your task consist of using the Python IDE below to complete the code needed to randomly generate a set of (x,y) coordinates (each between -150 and 150).

import random
x = random.randint(-150,150)
y = random.randint(-150,150)

Then you will need to implement the following flowchart using Python code to let the computer decide which cardinal point to use based on its randomly generated position.

Note that you will need to use the abs() function in python to get the absolute value.

e.g.

if x<0 and abs(x) >= abs(y):
   addBuoy("West", x, y)

Python Code:

Compete the code below:

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

Points of Sailing – Python Challenge

When sailing, the direction in which a boat can travel depends on the direction of the wind. Sailors describe the angle between the boat and the wind using different points of sailing, such as close-hauled, beam reach, broad reach and run.

In this Python challenge, you are going to write a program that uses the direction of the boat and the direction of the wind to work out the boat’s current point of sailing.

Boat and Wind Directions

Directions will be represented using angles between 0° and 360°:

  • 0° = North
  • 90° = East
  • 180° = South
  • 270° = West

Your program should start by asking the user to enter two values:

  1. The direction of the boat
  2. The direction the wind is coming from

For example:
Boat direction: 120°
Wind direction: 40°

We will use these two values to calculate the relative angle of the wind (relative to the direction of the boat). However, you cannot simply subtract these two values. Because directions wrap around at 360°, your program needs to calculate the relative wind angle correctly using the following algorithm:

For example, a boat travelling at 20° with the wind coming from 340° has a relative wind angle of only 40°.
The sign of the angle tells you which side of the boat the wind is coming from, while its magnitude tells you the boat’s point of sailing.

Points of Sailing

Once you have calculated the relative wind angle, use selection (if, elif and else) to work out the correct point of sailing.

Relative wind angle Point of sailing
−40° to +40° No-sail zone
40° to 55° Close-hauled
55° to 75° Close reach
75° to 105° Beam reach
105° to 145° Broad reach
145° to 170° Training run
170° to 180° Run

The same ranges apply on either side of the boat (for negative relative angles) This means, for example, that both +90° and −90°, represent a beam reach.

Python Challenge

Write a Python program that:

    Asks the user for the boat direction between 0° and 360°.
    Asks for the wind direction between 0° and 360°.
    Calculates the relative angle of the wind.
    Displays the relative wind angle.
    Uses an if / elif / else selection to identify the correct point of sailing.
    Displays the result to the user.

For example, your program might produce the following output:

Enter the boat direction (0-360): 120
Enter the wind direction (0-360): 40

Relative wind angle: -80 degrees
Point of sailing: Beam reach

Python Code

Complete the Python code below:

Online Points of Sailing Page

You can use our online interactive Points of Sailing page to understand more about the points of sailing and the position of the main sail and the jib on a sailing boat. You can use this page to help you test your program for different wind directions and boat directions.

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

Python Challenge – Speed, Distance & Time Calculator

Whether you are calculating the speed of a car, estimating how far a sound wave has travelled, or working out how long it takes light to reach the Earth, the relationship between speed, distance and time is used in many areas of science, engineering and everyday life.

The relationship is described using the following formula:

Speed = Distance ÷ Time

or, using letters and the / arithmetic symbol used by computer scientists instead of the ÷ symbol:

s = d / t

The same formula can be rearranged depending on which value we need to calculate:

  • Speed: s = d / t
  • Distance: d = s × t
  • Time: t = d / s

Python Challenge

In this Python challenge, you will create one program capable of performing all three calculations.

Your program should start by asking the user what they would like to calculate:

What would you like to calculate?
s - Speed
d - Distance
t - Time

The program will then need to make a decision based on the user’s answer.

For example, if the user chooses distance, the program should ask them to enter a speed and a time. It can then calculate the missing distance using:

distance = speed × time

If they choose speed, the program will need the distance and time, while calculating time will require the distance and speed.

This means your program will need to use selection with an if / elif / else statement to decide which calculation to perform.

Python Code

Complete the Python code below:

Example 1 – Calculating the Speed of a Car

Imagine a car travels 180 km in 2 hours.

The user selects s because they want to calculate the speed. Your program asks for the distance and time before calculating:

180 ÷ 2 = 90 km/h

So the program could display:

The speed is 90 km/h.

Example 2 – How Fast Does Sound Travel?

We can also use our program for a simple science experiment.

Imagine you are standing some distance from a large wall. You make a loud noise and measure how long it takes before you hear the echo.

Suppose the sound travels a total distance of 686 metres and takes 2 seconds to make the journey.

Using:

Speed = Distance ÷ Time

we get:

686 ÷ 2 = 343 m/s

This gives an approximate value for the speed of sound in air, which is around 343 metres per second under typical room-temperature conditions.

Remember: when using an echo, the sound travels to the wall and back again, so its total distance travelled is twice your distance from the wall.

Example 3 – The Speed of Light

Your program can even work with much larger numbers.

Light travels incredibly quickly through a vacuum: approximately 300,000 km/s.

The average distance between the Sun and Earth is about 150,000,000 km. We can therefore calculate approximately how long sunlight takes to reach us:

Time = Distance ÷ Speed 150,000,000 ÷ 300,000 = 500 seconds

That’s about 8 minutes and 20 seconds.

So when you look at the Sun, you are actually seeing light that left it more than eight minutes ago!

Programming Skills

To complete this challenge, you will need to combine several important Python programming skills:

  • Using input() to collect information from the user
  • Storing data using variables
  • Converting user inputs to float or int values
  • Performing arithmetic calculations
  • Using if, elif and else statements
  • Displaying calculated results using print(), and string concatenation

Extension Challenges

Once your basic program is working, see if you can improve it.

    Challenge 1: Ask the user which units they are using and include these units when displaying the answer.

    Challenge 2: Round calculated answers to two decimal places.

    Challenge 3: Detect invalid choices. What should happen if the user enters x instead of s, d or t?

    Challenge 4: Add a loop so that the user can perform several calculations without restarting the program.

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

Rubik’s Cube Challenge

Have you ever wondered how a computer keeps track of all the coloured squares on a Rubik’s Cube? Although the puzzle looks complicated, each face of the cube can actually be stored using a simple 3 × 3 two-dimensional (2D) array.

Instead of storing colours directly, programmers often represent each colour using a number from 1 to 6. For example:

    1: red
    2: white
    3: yellow
    4: orange
    5: green
    6: blue

A single face of the cube could therefore be stored like this:

In this Python challenge, your task is to complete a program that rotates one face of the Rubik’s Cube by 90 degrees. Using the flowchart provided, you will implement the algorithm needed to perform either a clockwise or an anti-clockwise rotation of the 2D array.

As you work through the challenge, you will discover how rows and columns change position during a rotation and how nested loops can be used to move data from one array into another. This is a great opportunity to practise working with 2D arrays, nested loops, indexing, and algorithmic thinking—skills that are widely used in computer graphics, games, image processing and artificial intelligence.

Algorithm Flowchart

Here is the flowchart to implement a rotation on a 2D-Array:

Python Code

Complete the following code using the algorithm described in the above flowchart

Extension Challenge

Once you have successfully rotated the 3 × 3 Rubik’s Cube face, take your solution one step further. Replace the array with a 4 × 4 version and see whether your algorithm still works correctly. Does your code depend on the array always being 3 × 3, or has it been written in a way that can rotate a square array of any size?

array = [[1, 2, 1, 4],
         [5, 4, 3, 5],
         [2, 1, 6, 3],
         [1, 4, 6, 2]]
unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

Autonomous Cave Exploration Drone Algorithm

Imagine being tasked with exploring a vast underground cave system where no human has ever been before. Narrow passages, uneven ceilings, jagged rocks and sudden drops make it far too dangerous for people to enter. Instead, scientists use autonomous drones to safely explore these hidden environments, mapping caves and collecting valuable data without putting anyone at risk.

In this activity, you’ll investigate the Python code used to control a cave exploration drone. Rather than being controlled by a pilot, the drone uses three infra-red distance sensors to detect obstacles in front of it. One sensor points diagonally upwards, one points straight ahead, and one points diagonally downwards. As the drone flies through the cave, these sensors constantly monitor the shape of the ceiling and the ground.

The Python program processes the information from the three sensors many times every second. If one of the sensors detects that the drone is getting too close to the cave walls, the program decides whether the drone should climb, descend or continue flying straight ahead. By repeatedly reading the sensors and adjusting its movement, the drone can navigate safely through the cave while avoiding collisions.

Here is the flowchart for the algorithm to control the drone:

As you work through the code, you will discover how programming, sensors and decision-making algorithms combine to create an autonomous system capable of reacting to its environment in real time. See if you can understand how the drone makes its decisions, then experiment with the code to improve its navigation or add your own ideas!

Python Code

Your Turn

As part of a space exploration project, an autonomous drone spacecraft will be sent on a journey through Jupiter’s asteroid belt. Your task is to reuse the Python code developed for the cave-exploration drone and adapt it for this new mission. Instead of detecting the cave’s ceiling and ground, the drone must use its three laser sensors to identify approaching asteroids and automatically adjust its vertical position to avoid a collision. Can you modify the existing navigation algorithm so the spacecraft can travel safely through space?

Python Code

You will need to update the code from line 48.

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

Sailing the Seven Seas (Python Challenge)

Long before radios and GPS, sailors relied on teamwork, experience and a good rhythm to keep a ship moving. One tradition that became famous around the world was the sea shanty. These songs were sung by crews as they hoisted sails, pulled ropes and weighed anchor, helping everyone work together in time. Many sea shanties also told stories of dangerous storms, distant lands and exciting adventures across the oceans.

Legend tells of a fearless pirate captain who sailed far beyond the known world. Wherever he travelled, his crew could be heard singing their favourite sea shanty, “Sailing the Seven Seas.” The song became so well known that sailors claimed they could recognise the pirate’s ship long before it appeared on the horizon!

According to the legend, when the pirate’s treasure was finally discovered, two mysterious pieces of parchment were found inside the treasure chest. The first parchment contained the lyrics to Sailing the Seven Seas… or so it seemed. Instead of words, it was filled with strange numbers. The second parchment contained a table matching each number to a word or short phrase.

At first, historians thought the pirate had created a secret code to stop rival pirates from stealing his famous song. However, computer scientists looking at the parchments noticed something interesting. Many words and phrases in the shanty were repeated over and over again, such as “Heave ho!”, “Raise the sail!” and “We are sailing the seven seas!”. Rather than writing these long phrases every time, the pirate had simply replaced them with short numbers and kept a lookup table on the second parchment.

Today, computers use a very similar idea when compressing data. Instead of storing the same information repeatedly, common words, patterns or sequences can be stored once and replaced with shorter references. Because the original text can be reconstructed perfectly using the lookup table, this is known as lossless compression.

In this challenge, you’ll become the pirate’s programmer! Your task is to complete the Python code provided to you by writing a function that uses a hash table (dictionary) to replace each number with its corresponding word or phrase, reconstructing the original lyrics to Sailing the Seven Seas. Can you successfully decode the pirate’s legendary sea shanty?

Python Code

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

A* Short Path Algorithm Interactive Task

Finding the shortest route between two places might sound like a simple task, but when a network contains hundreds or even millions of possible paths, computers need an efficient way to decide which route to follow. This is where search algorithms come in.

You may already have explored Dijkstra’s Shortest Path Algorithm, which guarantees finding the shortest path by systematically examining the graph. While Dijkstra’s algorithm is very reliable, it can sometimes spend time investigating routes that clearly lead away from the destination.

The A* (pronounced “A star”) algorithm improves on this idea by introducing a heuristic — an estimate of how far each node is from the destination. Instead of only considering the distance already travelled, A* also takes into account the estimated distance remaining. At each step, it chooses the node with the lowest combined value:

Total Cost = Distance from the Start + Estimated Distance to the Goal

By using this extra information, A* can focus its search towards the target instead of exploring every possible direction. In many real-world situations, this makes it significantly faster than Dijkstra’s algorithm while still guaranteeing the shortest path, provided the heuristic never overestimates the remaining distance.

Because of its efficiency, A* is one of the world’s most widely used pathfinding algorithms. It powers route-planning software, satellite navigation systems, robotics, video games, artificial intelligence, warehouse automation, and many other applications where computers need to navigate efficiently through complex environments.

In this interactive activity, you will practise applying the A* algorithm to a series of weighted directed graphs. For each challenge, use the heuristic values shown on the graph to calculate the total cost for each node, complete the A* table step by step, and determine the shortest path and its total distance. Compare your answers with the worked solution to build confidence in using one of the most important search algorithms in computer science.
A* Short Path AlgorithmOpen this activity in a New Window

Dijkstra Short Path Algorithm Interactive Task

Every time you use a sat nav, plan a journey on a map app, or search for the fastest route across a transport network, you are using ideas from graph theory. A road map can be represented as a graph: towns, junctions or stations are nodes, and the roads, railways or paths between them are edges. If each edge has a value, such as distance, time or cost, we can use an algorithm to find the shortest route.

One of the most famous algorithms for solving this problem is Dijkstra’s Shortest Path Algorithm. It was created in 1956 by Dutch computer scientist Edsger W. Dijkstra. The story goes that Dijkstra came up with the algorithm while sitting in a café in Amsterdam, trying to find an elegant way to calculate the shortest route between two cities. He later said that he designed it in about twenty minutes, without even using pencil and paper!

The algorithm works by starting at one node and gradually building up the shortest known distance to every other node in the graph. At each step, it chooses the unvisited node with the smallest temporary distance, marks it as visited, and updates the distances to its neighbouring nodes. By repeating this process, the algorithm eventually finds the shortest path from the starting node to the destination.

Dijkstra’s Algorithm is still important today. It has influenced route-planning systems, network routing, robotics, logistics, games, and many other areas of computer science. It is also a great example of how a problem can be solved by breaking it down into clear, repeatable steps.

In this interactive activity, you will practise applying Dijkstra’s Algorithm to a range of different weighted directed graphs. For each challenge, study the graph carefully, complete the table step by step, and identify the shortest path and total distance from the starting node to the target node. Use the check button to test your answers and improve your understanding of how the algorithm works.

Dijkstra Short Path AlgorithmOpen this activity in a New Window

Privacy Overview

This website will store some information about your preferences on your own computer inside a tiny file called a cookie. A cookie is a small piece of data that a website asks your browser to store on your computer or mobile device. The cookie allows the website to remember your actions or preferences over time.

You can delete all cookies that are already on your computer, and you can set most browsers to prevent them from being placed. However, if you do this, you may have to manually adjust some preferences every time you visit a site, and some services and functionalities may not work.

Most browsers support cookies, but you can set your browser to decline them and can delete them whenever you like. You can find instructions here for how you can do that on various browsers.

This website uses cookies to:

  1. Identify you as a returning user and to count your visits in traffic statistics analysis
  2. Remember your custom display preferences (such as light/dark theme option)
  3. Provide other usability features, including tracking whether you have already given your consent to cookies

Enabling cookies is not strictly necessary for the website to work but it will provide you with a better browsing experience.

The cookie-related information is not used to identify you personally and is not used for any purpose other than those described here.

There may also be other types of cookies created after you have visited this website. This site uses Google Analytics, a popular web analytics service that uses cookies to help to analyse how users use the site. The information generated by the cookie about your use of this website (including your IP address) will be transmitted to and stored by Google on servers in the United States. Google will use this information for the purpose of evaluating your use of other website, compiling reports on website activity, and providing other services relating to website activity and internet usage. Google may also transfer this information to third parties where required to do so by law, or where such third parties process the information on Google’s behalf. Google undertakes not to associate your IP address with any other data held by Google.